import Toast from 'tdesign-miniprogram/toast/index';
const basePage = require('../../common/BasePage')
Page({
  behaviors: [basePage],
  data: {
    /**地区信息 */
    area: {
      province: "",
      city: '',
      district: "",
      latitude: "",
      longitude: ""
    },
    imgSrcs: [],
    bannerArr: [],
    bgA: 0,
    goodsList: [],
    /**1 加载中；2 加载完；3 加载失败 */
    goodsListLoadStatus: 0,
    pageLoading: false,
    current: 1,
    autoplay: true,
    duration: '500',
    interval: 5000,
    navigation: {
      type: 'dots-bar'
    },
    swiperImageProps: {
      mode: 'scaleToFill',
      lazy: true
    },
    catArr: []
  },

  goodListPagination: {
    // index: 0,
    // num: 20,
    /**页码 */
    current: 0,
    /**每页条数 */
    size: 10
  },

  privateData: {
    tabIndex: 0,
  },

  onShow() {

    this.getTabBar().init();
    this.loadGoodsList();

    //更新定位
    let globalData = getApp().globalData;
    let latitude = globalData.latitude;
    let longitude = globalData.longitude;
    if (latitude && longitude) {
      let area = {
        ...this.data.area,
        latitude: latitude,
        longitude: longitude,
        street: globalData.areaName
      }
      this.setData({
        area: area
      })

    } else {
      wx.getLocation({
        type: "gcj02",
        success: (result) => {
          getApp().globalData.latitude = result.latitude;
          getApp().globalData.longitude = result.longitude;
          this.request({
            url: this.data.host + "/v1/user-address/city",
            method: 'post',
            data: {
              location: result.latitude + "," + result.longitude
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            }
          }, res => {
            let area = res.data.address_component
            this.setData({
              area: area
            });
            getApp().globalData.areaName = area.street || area.district || area.city || area.province;
            this.data.area.latitude = result.latitude;
            this.data.area.longitude = result.longitude;
          })
        },
        fail: (res) => {
          console.log('获取定位失败', res.errMsg);
          if (res.errMsg == 'getLocation:fail auth deny') {
            wx.showModal({
              cancelText: '取消',
              confirmColor: "#11C261",
              confirmText: '去授权',
              content: '请授权定位权限',
              showCancel: true,
              title: '提示',
              success: (result) => {
                if (result.confirm) {
                  wx.openSetting({
                    withSubscriptions: true,
                  })
                }
              },

            })
          }

        },
      })
    }

  },
  onTap(e) {
    console.log('ontap', e);
    let item = this.data.bannerArr[e.detail.index];
    if (item.linkUri) {
      wx.navigateTo({
        url: item.linkUri,

      })
    }
  },
  onLoad() {
    // this.init();
    this.request({
      url: this.data.host + '/v1/banner/banners',
    }, res => {
      console.log('this.data.host', res);
      let arr = [];
      res.data.map(val => {
        arr.push(this.data.imgHost + val.imagePath)
      })
      this.setData({
        imgSrcs: arr,
        bannerArr: res.data
      })
    })
    this.req_cats();

    wx.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline']
    });
  },
  req_cats() {
    this.request({
      url: this.data.host + '/v1/categories/program',
    }, res => {
      this.setData({
        catArr: res.data
      })

    })
  },
  area_click() {
    let area = this.data.area;
    wx.chooseLocation({
      latitude: area.latitude * 1,
      longitude: area.longitude * 1,
      success: (result) => {
        console.log('chooseLocation', result);
        getApp().globalData.latitude = result.latitude;
        getApp().globalData.longitude = result.longitude;
        getApp().globalData.areaName = result.name || result.address;
        this.setData({
          area: result
        })

      },

    })

  },
  onReachBottom() {
    if (this.data.goodsListLoadStatus === 0) {
      this.loadGoodsList();
    }
  },
  onPageScroll: function (ev) {
    // console.log('onPageScroll', ev);
    this.setData({
      bgA: ev.scrollTop / 200
    })
  },
  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.loadHomePage();
  },

  loadHomePage() {
    wx.stopPullDownRefresh();
    this.loadGoodsList(true);

  },
  test_click() {
    console.log('test_click');
    wx.scanCode({

      scanType: ['qrCode', 'barCode'],
      success: (result) => {
        console.log('扫码成功', result);
        wx.setStorageSync('src', result.result)
        wx.navigateTo({
          url: '/pages/web/view',

        })
      },
      fail: (res) => {
        console.log('扫码失败', res);
      },
      complete: (res) => {},
    })
  },
  tabChangeHandle(e) {
    this.privateData.tabIndex = e.detail;
    this.loadGoodsList(true);
  },

  onReTry() {
    this.loadGoodsList();
  },

  async loadGoodsList(fresh = false) {
    if (fresh) {
      wx.pageScrollTo({
        scrollTop: 0,
      });
    }

    this.setData({
      goodsListLoadStatus: 1
    });

    // const pageSize = this.goodListPagination.num;
    // let pageIndex = this.privateData.tabIndex * pageSize + this.goodListPagination.index + 1;

    if (fresh) {
      // pageIndex = 0;
      this.goodListPagination.current = 0;
    }
    this.goodListPagination.current++;

    try {

      let goodListPagination = this.goodListPagination;
      let goodsList = this.data.goodsList;
      this.request({
        url: this.data.host + '/v1/goods/home',
        data: {
          ...goodListPagination
        }
      }, res => {

        if (goodListPagination.current == 1) {
          goodsList = res.data.records;
        } else {
          goodsList = goodsList.concat(res.data.records)
        }
        this.setData({
          goodsList: goodsList,
          goodsListLoadStatus: res.data.current * res.data.size >= res.data.total * 1 ? 2 : 1
        })

      })

    } catch (err) {
      this.setData({
        goodsListLoadStatus: 3
      });
    }
  },

  goodListClickHandle(e) {
    console.log('goodListClickHandle', e);
    let goods = e.detail.goods;
    wx.setStorage({
      key: "goods",
      data: goods
    })
    // wx.switchTab({
    //   url: '/pages/store/nearby?goodsSid='+goods.sid+"&firstLevelSid="+goods.firstLevelSid,
    // })
    wx.reLaunch({
      url: '/pages/store/nearby?goodsSid=' + goods.sid + "&firstLevelSid=" + goods.firstLevelSid,
    })


  },

  goodListAddCartHandle() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '点击加入购物车',
    });
  },
  find_click() {
    let userInfo = getApp().globalData.userInfo;
    // console.log('search_click', userInfo);
    if (!userInfo || !userInfo.cardNumber) {
      this.request({
        url: this.data.host + "/v1/users/me"
      }, res => {
        getApp().globalData.userInfo = res.data;
        if (res.data.cardNumber) {
          wx.navigateTo({
            url: '/pages/goods/find'
          });
        } else {
          wx.showModal({
            showCancel: true,
            title: '提示',
            content: "需实名认证才可以使用该功能哦",
            confirmColor: "#23BC97",
            success: (result) => {
              if (result.confirm) {
                wx.redirectTo({
                  url: '/pages/usercenter/identity',
                })
              }
            },

          })
        }
      })

    } else {
      wx.navigateTo({
        url: '/pages/goods/find'
      });
    }
  },
  search_click() {
    let userInfo = getApp().globalData.userInfo;
    // console.log('search_click', userInfo);
    if (!userInfo || !userInfo.cardNumber) {
      this.request({
        url: this.data.host + "/v1/users/me"
      }, res => {
        // console.log("/v1/users/me", res);
        getApp().globalData.userInfo = res.data;
        if (res.data.cardNumber) {
          wx.navigateTo({
            url: '/pages/goods/search/all'
          });
        } else {
          wx.showModal({
            showCancel: true,
            title: '提示',
            content: "需实名认证才可以使用该功能哦",
            confirmColor: "#23BC97",
            success: (result) => {
              if (result.confirm) {
                wx.redirectTo({
                  url: '/pages/usercenter/identity',
                })
              }
            },

          })
        }
      })

    } else {
      wx.navigateTo({
        url: '/pages/goods/search/all'
      });
    }
  },
  navToSearchPage(e) {

    wx.navigateTo({
      url: '/pages/goods/search/index?index=' + (e.currentTarget.dataset.index || 0)
    });
  },

  navToActivityDetail({
    detail
  }) {
    const {
      index: promotionID = 0
    } = detail || {};
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },
});